package org.lee.img;

import javax.swing.*;
import java.awt.*;

/**
 * ScaleIconDemo
 * 缩放图片
 *
 * @author dralee
 * @date 2021-12-29 16:14:31
 **/
public class ScaleIconDemo extends JFrame {
    public ScaleIconDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        ImageIcon orgIcon = new ImageIcon(getClass().getClassLoader().getResource("images/icon.png"));
        JLabel orgLbl = new JLabel(orgIcon);
        int width = orgIcon.getIconWidth() / 2;
        int height = orgIcon.getIconHeight() / 2;

        Image scaled = scaleImage(orgIcon.getImage(), width, height);
        ImageIcon scaledIcon = new ImageIcon(scaled);
        JLabel lbl = new JLabel(scaledIcon);

        Image scaled2 = scaleImage(orgIcon.getImage(), width / 2, height / 2);
        ImageIcon scaledIcon2 = new ImageIcon(scaled2);
        JLabel lbl2 = new JLabel(scaledIcon2);

        createLayout(orgLbl, lbl, lbl2);

        setTitle("Scaled icon");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {
        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);
        gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]).addComponent(arg[1]).addComponent(arg[2]));
        gl.setVerticalGroup(gl.createParallelGroup().addComponent(arg[0]).addComponent(arg[1]).addComponent(arg[2]));

        pack();
    }

    private Image scaleImage(Image image, int width, int height) {
        return image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ScaleIconDemo().setVisible(true));
    }
}
